<?php
namespace Cyfy\Modules\BasicContent\Forms;

use \Cyfy\Message;
use \Cyfy\Modules\Forms;
use \Cyfy\Modules\BasicContent\Content;

/**
 * Creates a new block.
 */
class EditBlock extends Forms\Form
{
    public $bcData = array();
    
	function structure()
	{
        $this -> stay = true;
        $this -> permission('BasicContent', 'edit own');
        
        // LANGUAGES
        $t = new Forms\TabSet("texts", "Texts");
        $t -> defaultTab = ($_GET['language']) ? $_GET['language'] : \Cyfy\Language :: getActive();
          
        foreach(\Cyfy\Language :: getAll() as $lg => $language)
        {
            $bc = (array) $this -> bcData[$lg];
            
            $t -> addTab($lg, $language);
            $i = new Forms\TextBox("title[$lg]", self :: t(20));
            $i -> maxlength = 255;
            if($bc){
                $i -> value = (string) $bc['title'];
            }
            $t -> addItem($lg, $i);
            $w = new Forms\WysiwygEditor("content[$lg]", self :: t(40));
            if($bc){
                $w -> value = (string) $bc['content'];
            }
            $t -> addItem($lg, $w);
        }
        
        $this -> addItem($t);
        
        $this -> wysiwygForm = true;
		
        $i = new Forms\Hidden("bcid");
		$this -> addItem($i);
        
		$b = new Forms\Button(self :: t(540), Forms\Button::OK);
		$this -> addButton($b);		
    }
  
    function submit()
	{  
		$bcid = $this -> get("bcid");
        
        // a little hack while using POST
        $titles = $_POST['title'];
        $contents =  $_POST['content'];
        
        foreach(\Cyfy\Language :: getAll() as $lg => $language)
        {
            if($contents[$lg])
            {
                $title = ($titles[$lg]) ? $titles[$lg] : "";
                $content = $contents[$lg];
                
                $content = new Content($title, $content, $lg);
                $content -> setBCID($bcid);
                
                if(!$content -> save())
                {
                    Message :: set(self :: t(551, array($language)), Message::ERROR);
                }
            }
        }
        
		Message :: set(self :: t(561, array($this -> get("title"))));
        
        \Cyfy\Blocks :: runOnce();
        $this -> onSubmit = "Blocks.reload('BasicContent', '$bcid');";

        return true;
	}
}
